package com.kx.kxblog.util;

import com.kx.kxblog.entity.User;
import com.kx.kxblog.enums.ResultCode;
import com.kx.kxblog.enums.SystemContextKey;
import com.kx.kxblog.enums.SystemContextKeySavePath;
import com.kx.kxblog.exception.ResultException;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class SystemContext implements AutoCloseable {
    private static final ThreadLocal<Map<Object,Object>> threadLocal = new ThreadLocal<>();
    public static void put(SystemContextKey key,Object obj){
        Map<Object,Object> map = threadLocal.get();
        if(map==null){
            map = new HashMap<>();
            threadLocal.set(map);
        }
        if(key.getPath()==SystemContextKeySavePath.THREAD_LOCAL) {
            map.put(key, obj);
        } else if(key.getPath()==SystemContextKeySavePath.SESSION){
            HttpSession session = (HttpSession) map.get(SystemContextKey.SESSION);
            if(session==null)
                throw new IllegalStateException("Session未设置");
            session.setAttribute(key.name(), obj);
        }
    }
    public static Object get(SystemContextKey key){
        Map<Object, Object> map = threadLocal.get();
        if(map==null) return null;
        if(key.getPath()== SystemContextKeySavePath.THREAD_LOCAL) {
            return map.get(key);
        }
        else if(key.getPath() == SystemContextKeySavePath.SESSION){
            // 去session里找
            HttpSession session = (HttpSession) map.get(SystemContextKey.SESSION);
            if(session!=null){
                return session.getAttribute(key.name());
            }
        }
        return null;
    }

    public static User getLoginUser(){
        return (User) get(SystemContextKey.USER);
    }

    public static User checkLoginUser(){
        User user = getLoginUser();
        if(user==null)
            throw new ResultException(ResultCode.UNLOGIN);
        return user;
    }

    @Override
    public void close(){
        threadLocal.remove();
    }
}
